<?php

namespace app\controller\admin;

use app\model\admin\Admin;
use app\model\admin\AdminLoginLog;

class Login
{
    // 登录
    public function login()
    {
        $data = request()->post();
        if (empty($data['account']) || empty($data['password'])) {
            data_return('用户名或密码不能为空', -1);
        }
        $admin = (new Admin())->data_get(['username' => $data['account']]);
        if (!$admin) {
            data_return('账号不存在', -1);
        }


        $errKey = 'admin_login_err_' . $data['account'];
        $errorCount = intval(cache($errKey));//错误次数
        $lockKey = $errKey . '_lock_time';
        $lockTime = cache($lockKey);
        if ($lockTime && $lockTime > time()) {
            data_return('账号已锁定，请' . ($lockTime - time()) . '秒后重试', -1, $lockTime);
        }

        if ($admin['password'] != md5($data['password'] . $admin['salt'])) {
            cache($errKey, $errorCount + 1, 300);
            if ($errorCount > 5) {
                cache($lockKey, time() + 300, 300);
                data_return('账号已锁定，请5分钟后重试', -1, $lockTime);
            }
            data_return('密码错误,您还可以重试' . (5 - $errorCount) . '次密码', -1);
        }
        cache($errKey, null);
        cache($lockKey, null);

        //10位随机数
        $salt = substr(md5(uniqid()), 0, 10);
        $pwd = md5($data['password'] . $salt);
        $up = [
            'password' => $pwd,
            'salt' => $salt,
            'last_login_ip' => request()->ip(),
            'last_login_time' => date('Y-m-d H:i:s'),
        ];
        $token = md5(uniqid() . time());
        (new Admin())->data_update(['admin_id' => $admin['admin_id']], $up);
        $expire_time = 86400 * 7;
        (new AdminLoginLog())->data_add([
            'admin_id' => $admin['admin_id'],
            'ip' => request()->ip(),
            'token' => $token,//登录token，兼容以后统一登录
            'expire' => $expire_time,//过期时间，方便以后统一登录
        ]);
        cache('admin_' . $token, $admin, $expire_time);
        data_return('登录成功', 0, ['token' => $token]);
    }

    // 退出
    public function logout()
    {
        $token = request()->header('Authorization');
        $token = str_replace('Bearer ', '', $token);
        if ($token) {
            cache('admin_' . $token, null);
            (new AdminLoginLog())->data_update(['token' => $token], ['expire' => 0]);
        }
        data_return('退出成功', 0);
    }
}
